<template>
  <div class="list-sent-section">
    <div class="list-section-main">
      <div class="list-section-top"
           v-if="urlParamObj.name">
        <span>{{ urlParamObj.name }}</span>
        <span v-if="showTotal">({{ pagination.total }})</span>
      </div>
      <div :id="searchConditionContainerId"></div>
      <div class="list-section-header">
        <CommonCounter v-if="selectedRows.length"
                       :total="pagination.total"
                       :currentSelected="selectedRows.length"
                       @cancelSelected="cancelSelected" />
        <div class="toolbar-setting">
          <CommonToolbar :allToolBtns="allToolBtns"
                         @buttonClick="buttonClick"> </CommonToolbar>
        </div>
        <div class="search-part">
          <div class="search-action">
            <a-input-search :placeholder="$i18n('collaboration.new.template.search.keyWords')"
                            style="width: 272px"
                            :allowClear="true"
                            @change="onInputSearchValueChange"
                            @search="onSearch" />
          </div>
          <div class="search-condition-class">
            <SearchCondition :containerParentId="searchConditionContainerId"
                             :conditions="searchConditions"
                             @valueChange="conditionValueChange"
                             @expandChange="expandChange"></SearchCondition>
          </div>
        </div>
      </div>

      <div class="list-section-content">
        <div>
          <AVirtuallyTable ref="avirtuallyTable"
                           rowKey="id"
                           :pagination="true"
                           :paginationOption="pagination"
                           :columns="columns"
                           :openVirtuallyModel="true"
                           :dataSource="dataSource"
                           size="small"
                           :bordered="false"
                           :loading="loading"
                           :localstorageKey="getLocalStorageKey"
                           @paginationChange="handleTableChange"
                           @paginationShowSizeChange="paginationShowSizeChange"
                           @rowClick="rowClick">
            <span slot="subject"
                  slot-scope="{ record }">
              <SubjectRender :slotData="record"
                             :urlParams="urlParamObj"
                             :hasToTop="false">
              </SubjectRender>
            </span>
            <span slot="deadLine"
                  slot-scope="{ text, record }">
              <span v-if="record.dealTimeout"
                    :title="text"
                    class="color_red left flagClass text_overflow">
                {{ text }}
              </span>
            </span>
            <span slot="categoryLabel"
                  slot-scope="{ text, record }">
              <CategoryLabel :text="text"
                             :urlParams="urlParamObj"
                             :slotData="record"
                             :isRegistRole="isRegistRole"
                             @openLink="linkToSent">
              </CategoryLabel>
            </span>

            <span slot="currentNodesInfo"
                  slot-scope="{ text, record }">
              <span v-if="text && record.processId"
                    class="current-nodes"
                    :title="text"
                    @click.stop="showFlowChart(record)">{{ text }}</span>
            </span>
          </AVirtuallyTable>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  //展现流程图，工作流的js会用到
  window._wfctxPath = _ctxPath;
  /* global axios,_ctxPath, CsrfGuard, collaborationApi, getCtpTop, _hasResource */
  import { getParams, loadComponentsThemeDefaultCSS } from '../../utils';
  import CommonCounter from '../../components/common-counter/index';
  import CommonToolbar from '../../components/common-toolbar/index';
  import SearchCondition from '@/components/search-condition/index.vue';
  import AVirtuallyTable from '@/ant-virtually-table/table.vue';
  import SubjectRender from '../../components/subject-render/index.vue';
  import CategoryLabel from '../../components/category-label/index.vue';
  import collaboration from '../../utils/collaboration.js';
  import smartCodeMixin from '../../mixins/smart-code-mixin';
  import { formatRequestDataToJSON, loadExtendResource } from '@/utils/api';

  export default {
    name: 'ListSentSection',
    mixins: [smartCodeMixin],
    components: {
      CommonCounter,
      CommonToolbar,
      SearchCondition,
      AVirtuallyTable,
      SubjectRender,
      CategoryLabel
    },
    data() {
      return {
        showTotal: false,
        allToolBtns: [],
        showCounter: false,
        searchConditionContainerId: 'search-condition-container-parent',
        dataSource: [],
        columns: [],
        selectedRowKeys: [],
        urlParamObj: {},
        pagination: {
          page: 1,
          total: 0
        },
        searchValue: '',
        selectedRows: [],
        searchConditions: [],
        loading: false
      };
    },
    computed: {
      getLocalStorageKey() {
        return `${this.userId}LIST_SENT_SECTION`;
      }
    },
    created() {
      this.initParams();
      this.initTableHeader();
      this.initTableData();
      window.closeAndFresh = this.initTableData;
      window.addEventListener('storage', this.bindStorage);
      loadComponentsThemeDefaultCSS(window._ctxPath + window._ctpSkinUrl);
    },
    mounted() {},
    methods: {
      initParams() {
        this.isRegistRole = false;
        this.userId = window._currentUser.id;
        //按钮由前端写死
        this.urlParamObj = getParams(window.location.search);
        this.urlParamObj.name
          ? (this.urlParamObj.name = window.decodeURIComponent(this.urlParamObj.name))
          : '';
        this.isTop = false;
        this.needRefresh = false;
        this.isV5Member = false;
        //高级条件
        this.seniorConditions = null;
      },
      initToolbar() {
        if (this.isHaveSmartCodePermission()) {
          this.allToolBtns.push(this.smartCodeBtnInfo);
        }
      },
      initTableHeader() {
        const headerParams = {
          // 页面唯一标识（取值参照PageKey）
          key: 'LIST_SENT_SECTION',
          // 来源 0菜单 1栏目 （取值参照FromType）
          // from: 1,
          // 终端 0 pc 1 mobile （取值参照PlatformType）
          platform: 0,
          // 业务传参，由业务决定（后续可在元数据拦截器中获取到）
          arguments: {
            fragmentId: this.urlParamObj.fragmentId || '',
            ordinal: this.urlParamObj.ordinal || '',
            bigTitleIndex: this.urlParamObj.bigTitleIndex || '',
            userId: window._currentUser.id
          }
        };
        const url = `${_ctxPath}/rest/global/metadata/list`;
        axios.post(url, headerParams).then((data) => {
          if (data.data.code === 0) {
            const recieveData = data.data.data;
            loadExtendResource(recieveData.extra?.extendResources);
            this.hanlderHeader(recieveData);
            // this.columns = recieveData.tableColumns;
            this.initToolbar();
          }
        });
      },
      hanlderHeader(data) {
        if (data) {
          let { tableColumns, searchConditions, globalParam } = data;
          this.searchConditions = searchConditions.filter((item) => item.key !== 'subject');
          this.isV5Member = globalParam.v5Member;
          this.isRegistRole = globalParam.registRole;
          this.supportSmartCode = globalParam ? globalParam.supportSmartCode : undefined;
          if (this.isV5Member) {
            getCtpTop().hideLocation && getCtpTop().hideLocation();
          }

          const customArr = ['subject', 'categoryLabel', 'currentNodesInfo'];
          let tableColumnsResult = tableColumns.filter((item) => {
            delete item.extra;
            item.dataIndex = item.key;
            if (customArr.includes(item.key)) {
              item.scopedSlots = { customRender: item.key };
            }
            item.dropdownMenus = {
              fieldset: true
            };
            if (item.key !== 'operation') {
              item.dropdownMenus.desc = true;
              item.dropdownMenus.asc = true;
            }
            item.customCell = () => {
              return {
                style: {
                  cursor: 'pointer',
                  padding: '0 8px'
                }
              };
            };

            if (item.key === 'workitemId') {
              return false;
            } else {
              return true;
            }
          });
          // tableColumnsResult[0].width = 1000;
          this.columns = tableColumnsResult;
        }
      },

      initTableData() {
        this.loading = true;
        let sendSearch;
        let requestData = `managerMethod=getMoreList4SectionContion&arguments=`;
        if (this.seniorConditions) {
          sendSearch = this.seniorConditions;
        } else {
          const { fragmentId = '', ordinal = '', bigTitleIndex = '' } = this.urlParamObj;

          const initParams = {
            fragmentId,
            state: '2',
            ordinal,
            bigTitleIndex,
            isTrack: 'false',
            condition: 'subject',
            textfield: this.searchValue || ''
          };
          sendSearch = initParams;
          this.seniorConditions = initParams;
        }
        const pageInfo = {
          page: this.pagination.page
        };
        if (this.pagination.pageSize) {
          pageInfo.size = this.pagination.pageSize;
        }
        const sendParams = [pageInfo, sendSearch];
        const args = `${requestData}${formatRequestDataToJSON(sendParams)}`;

        const url = `${_ctxPath}/ajax.do?method=ajaxAction&managerName=pendingManager&rnd=${this.getRandom()}`;

        if (this.cancelToken && this.cancelToken.cancel) {
          this.cancelToken.cancel();
          this.cancelToken = null;
        }
        this.cancelToken = axios.CancelToken.source();

        axios.post(url, args, { cancelToken: this.cancelToken.token }).then((data) => {
          const result = data.data;
          if (result) {
            // this.pagination.total = result.total;
            this.dataSource = result.data;
            this.pagination.total = result.total;
            this.showTotal = true;
            this.loading = false;
          }
          window.parent.refreshMenuList && window.parent.refreshMenuList();
        });
      },
      expandChange() {
        this.$nextTick(() => {
          this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.resizeTable();
        });
      },
      onInputSearchValueChange(e) {
        this.searchValue = e.target.value;
        if (typeof this.seniorConditions.textfield !== 'undefined') {
          this.seniorConditions.textfield = this.searchValue;
        } else {
          this.seniorConditions.subject = this.searchValue;
        }
      },
      onSearch(e) {
        this.searchValue = e;
        if (typeof this.seniorConditions.textfield !== 'undefined') {
          this.seniorConditions.textfield = this.searchValue;
        } else {
          this.seniorConditions.subject = this.searchValue;
        }
        this.pagination = { ...this.pagination, page: 1 };
        this.initTableData();
      },
      cancelSelected() {
        this.showCounter = false;
        this.selectedRows = [];
        this.selectedRowKeys = [];
      },
      //按钮点击事件
      buttonClick(buttonKey) {
        if (buttonKey === 'smartCodeScan') {
          this.showSmartCode && this.showSmartCode();
          return;
        }
      },
      handleTableChange(page, pageSize) {
        this.pagination.page = page;
        this.pagination.pageSize = pageSize;
        this.initTableData();
      },

      paginationShowSizeChange(current, size) {
        this.pagination.page = 1;
        this.pagination.pageSize = size;
        this.initTableData();
        //TODO: 进行筛选
      },
      linkToSent(record) {
        const { applicationCategoryKey: app, applicationSubCategoryKey: subApp } = record;
        const urlObjs = {
          F20_govDocSendManage: `${_ctxPath}/govdoc/govdoc.do?method=index&listType=listSent&govdocType=1&_resourceCode=F20_govDocSendManage`,
          F20_gocDovSend: `${_ctxPath}/govdoc/govdoc.do?method=index&listType=listSentAllRoot&_resourceCode=F20_gocDovSend`,
          F20_receiveManage: `${_ctxPath}/govdoc/govdoc.do?method=index&listType=listSent&govdocType=2,4&_resourceCode=F20_receiveManage`,
          F20_signReport: `${_ctxPath}/govdoc/govdoc.do?method=index&listType=listSent&govdocType=3&_resourceCode=F20_signReport`,
          other_listSent: `${_ctxPath}/collaboration/collaboration.do?method=listSent${CsrfGuard.getUrlSurffix()}&showTab=true`
        };
        const hasGocDovSend = _hasResource('F20_gocDovSend');
        if (app === 4) {
          //表单公文重构
          if (subApp === 1 || subApp === 19) {
            //公文-发文
            if (_hasResource('F20_govDocSendManage')) {
              window.location.href = urlObjs['F20_govDocSendManage'];
            } else if (hasGocDovSend) {
              window.location.href = urlObjs['F20_gocDovSend'];
            }
          } else if (subApp === 2 || subApp === 4 || subApp === 20) {
            //公文-收文
            if (_hasResource('F20_receiveManage')) {
              window.location.href = urlObjs['F20_receiveManage'];
            } else if (hasGocDovSend) {
              window.location.href = urlObjs['F20_gocDovSend'];
            }
          } else if (subApp === 3 || subApp === 21) {
            //公文-签报
            if (_hasResource('F20_signReport')) {
              window.location.href = urlObjs['F20_signReport'];
            } else if (hasGocDovSend) {
              window.location.href = urlObjs['F20_gocDovSend'];
            }
          }
        } else {
          window.location.href = urlObjs['other_listSent'];
        }
      },
      rowClick(record) {
        if (this.isTop) {
          this.isTop = false;
          return;
        }
        this.linkToSummary(record);
      },

      bindStorage(event) {
        if (event.key == 'sendEvent') {
          this.initTableData();
        }
      },
      conditionValueChange(data, result) {
        this.pagination.page = 1;
        const { fragmentId = '', ordinal = '', bigTitleIndex = '' } = this.urlParamObj;
        const seniorSearch = {
          subject: this.searchValue || '',
          ...result,
          fragmentId,
          state: '2',
          ordinal,
          bigTitleIndex,
          isTrack: 'false',
          condition: 'comQuery'
        };
        this.seniorConditions = seniorSearch;
        this.initTableData();
      },
      //显示流程图
      showFlowChart(record) {
        const { caseId, processId, activityId, applicationCategoryKey, bodyType } = record;

        const options = {
          targetWin: getCtpTop(),
          caseId: caseId,
          processId: processId,
          isTemplate: false,
          showHastenButton: false,
          appName: applicationCategoryKey,
          currentNodeId: activityId,
          scene: 3,
          canExePrediction: bodyType === '20' && window._hasPlugin('workflowAdvanced')
        };
        window.showDiagram(options);
      },
      linkToSummary(record) {
        const {
          id: affairId,
          applicationCategoryKey: app,
          applicationSubCategoryKey: subApp
        } = record;
        let url = `${_ctxPath}/collaboration/collaboration.do?method=summary&openFrom=listSent&affairId=${affairId}&showTab=true`;
        if (app == 4) {
          if (subApp === 19 || subApp === 20 || subApp === 21) {
            //公文已发详细from参数值统一改为listSent
            url = ` ${_ctxPath}/edocController.do?method=detail&from=listSent&affairId=${affairId}`;
          } else if (subApp === 1 || subApp === 2 || subApp === 3 || subApp === 4) {
            //G6 6.1 新表单公文
            url = `${_ctxPath}/govdoc/govdoc.do?method=summary&openFrom=listSent&affairId=${affairId}`;
          }
        }
        collaborationApi.showSummayDialogByURL(url);
      },
      // 智码扫码成功后，智码预处理时，获取解码参数
      getSmartCodeDecodeParam() {
        const obj = this.seniorSearch;
        obj.openFrom = 'moreSent';
        return obj;
      },
      // 智码扫码成功后回调
      smartCodeCallBack(data) {
        collaboration.smartCodeCallBack(data);
      },
      getRandom() {
        return Math.floor(Math.random() * Math.pow(10, 5));
      }
    },
    beforeDestroy() {
      window.removeEventListener('storage', this.bindStorage);
      delete window.closeAndFresh;
      delete window._wfctxPath;
    }
  };
</script>

<style>
  @import url('../../assets/css/common.css');
</style>
<style lang="scss">
  .list-sent-section {
    position: relative;
    height: 100%;
    .list-section-main {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      top: 0;
      display: flex;
      padding-left: 16px;
      flex-direction: column;
      background-color: #ffffff;
      // background-color: #F9FAFC;
      .list-section-top {
        padding: 12px 16px 0 0;
        font-size: 16px;
        font-weight: 600;
        color: #333333;
      }
      .list-section-header {
        display: flex;
        padding: 12px 16px 12px 0;
        height: 54px;
        box-sizing: border-box;
      }
      .toolbar-setting {
        flex: 1;
        overflow: hidden;
      }
      .search-action {
        display: inline-block;
        width: 272px;
      }
      .search-part {
        // flex: 1;
        display: flex;
        justify-content: flex-end;
        overflow: hidden;
        margin-left: 100px;
      }

      .list-section-content {
        flex: 1;
        padding: 0;
        position: relative;
        overflow: hidden;
        > div {
          position: absolute;
          top: 0;
          right: 0;
          bottom: 0;
          left: 0;
        }
      }
      .titleText-improtant {
        display: inline-block;
        max-width: 85%;
        max-width: calc(100% - 100px);
        overflow: hidden;
        white-space: nowrap;
        // float: left;
        text-overflow: ellipsis;
      }
      .important-level {
        // width: 32px;
        height: 18px;
        line-height: 16px;
        border-radius: 2px;
        text-align: center;
        margin-right: 4px;
        margin-left: -2px;
        font-family: PingFangSC-Semibold;
        font-weight: 600;
        display: inline-block;
        font-size: 12px;
        transform: scale(0.83);
        padding: 1px 3px;
        color: #ffffff;
        letter-spacing: 0;
        border: none;
        cursor: pointer;
      }

      .important-level-2 {
        background: #3759ec;
      }

      .important-level-3 {
        background: #ffa324;
      }

      .important-level-4 {
        background: #fc6c1d;
      }

      .important-level-5 {
        background: #fa3d12;
      }
      .current-nodes:hover {
        color: #318ed9;
        color: var(--theme-brand5, #318ed9);
      }
      .search-condition-class {
        margin-left: 12px;
        display: flex;
      }
    }
  }
</style>
